package com.zxd.interview.eightthread.threadobjectclasscommonmethod;

/**
 * 演示wait方法使用
 * 1.研究代码的执行顺序
 * 2. 证明wait释放锁
 * @author Xander
 * @version v1.0.0
 * @Package : com.zxd.interview.eightthread.threadobjectclasscommonmethod
 * @Description : 演示wait方法使用
 * @Create on : 2023/3/12 09:57
 **/
public class Wait {


    public static Object object = new Object();

    public static void main(String[] args) throws InterruptedException {
        new Thread1().start();
        Thread.sleep(1000);
        new Thread2().start();
    }

    /**
     * 结果
     * 解释：
     * 1. synchronized 的代码往下执行的条件是

     线程Thread-0 开始执行
     线程Thread-0 进行wait()
     线程Thread-1 调用了notify
     线程Thread-0 被唤醒，继续执行
     线程Thread-0 获取到了锁


     */

    static class Thread1 extends Thread {

        @Override
        public void run() {
            synchronized (object) {
                System.out.println("线程" + Thread.currentThread().getName() +  " 开始执行");
                try {
                    System.out.println("线程" + Thread.currentThread().getName() +  " 进入wait()");
                    object.wait();

                    System.out.println("线程" + Thread.currentThread().getName() +  " 被唤醒，继续执行");
                } catch (InterruptedException e) {
                    // 中断异常
                    e.printStackTrace();
                }
                System.out.println("线程" + Thread.currentThread().getName() + " 获取到了锁");
            }
        }
    }


    static class Thread2 extends Thread {
        @Override
        public void run() {
            try {
                synchronized (object) {

                    Thread.sleep(1000);
                    object.notify();
                    System.out.println("线程" + Thread.currentThread().getName() + " 调用了notify");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
